package com.huluwa.jczq.util;


import com.jcraft.jsch.*;
import com.kiwi.action.LoginAction;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.logicalcobwebs.concurrent.FJTask;


import java.io.*;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Properties;

import static com.huluwa.jczq.common.Constant.*;

/**
 * Created by hancc on 2018/6/18.
 */
public class GetLog {
   private static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(LoginAction.class);
   private static ChannelExec channelExec;
   private static Session session = null;
   private static int timeout = 60000;

   /**
    * 连接远程服务器
    * @param host ip地址
    * @param userName 登录名
    * @param password 密码
    * @param port 端口
    * @throws Exception
    */
   public void versouSshUtil(String host,int port,String userName,String password) throws Exception{
      logger.info("尝试连接到....host:" + host + ",username:" + userName + ",password:" + password + ",port:"
              + port);
//        String keyFile = "C:\\Users\\bjwangzheng3\\Desktop\\secret\\wangzheng";
      JSch jsch = new JSch(); // 创建JSch对象
//        jsch.addIdentity(keyFile);
      session = jsch.getSession(userName, host, port); // 根据用户名，主机ip，端口获取一个Session对象
//        MyUserInfo myUserInfo = new MyUserInfo(password);
//        session.setUserInfo(myUserInfo);
      session.setPassword(password); // 设置密码
      Properties config = new Properties();
      config.put("StrictHostKeyChecking", "no");
      session.setConfig(config); // 为Session对象设置properties
      session.setTimeout(timeout); // 设置timeout时间
      session.connect(); // 通过Session建立链接
   }

   /**
    * 在远程服务器上执行命令
    * @param cmd 要执行的命令字符串
    * @param charset 编码
    * @throws Exception
    */
   public String runCmd(String cmd,String charset) throws Exception{
      channelExec = (ChannelExec) session.openChannel("exec");
      channelExec.setCommand(cmd);
      channelExec.setInputStream(null);
      channelExec.setErrStream(System.err);
      channelExec.connect();
      InputStream in = channelExec.getInputStream();
      BufferedReader reader = new BufferedReader(new InputStreamReader(in, Charset.forName(charset)));
      String buf = null;
      String msg = "";
      while ((buf = reader.readLine()) != null){
         //System.out.println(buf);
         msg += buf;
      }
      reader.close();
      channelExec.disconnect();
      msg = msg.substring(msg.indexOf("】")+1);
      return msg;
   }

   public String readToString(String fileName) {
      String encoding = "UTF-8";
      File file = new File(fileName);
      Long filelength = file.length();
      byte[] filecontent = new byte[filelength.intValue()];
      try {
         FileInputStream in = new FileInputStream(file);
         in.read(filecontent);
         in.close();
      } catch (FileNotFoundException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      }
      try {
         return new String(filecontent, encoding);
      } catch (UnsupportedEncodingException e) {
         System.err.println("The OS does not support " + encoding);
         e.printStackTrace();
         return null;
      }
   }

   //通过ticketId打印日志
   public void getLogByTicketId(String ticketId,String getMessageCmd)  {
      String getMessage = "";
     // String originMsg = getMessage.substring(getMessage.indexOf(keyStart)+keyStart.length(),getMessage.indexOf(keyEnd));
      try {
            getMessage = runCmd(getMessageCmd,"UTF-8");

      } catch (Exception e) {
         logger.error("找不到这张票的日志，ticketId:"+ticketId);
         e.printStackTrace();
         return;
      }
      logger.info("ticketId:"+ticketId);
      logger.info("log:"+getMessage);

   }
   public final static String betSelector = " \"【0】.*{ticketId}.*\" ";
   // 测试代码
   public static void main(String[] args) throws Exception {

      String getMessageXml = "<?xml version=\"1.0\" encoding=\"gb2312\"?>\n" +
              "<ActionResult>\n" +
              "    <xMsgID>9003122018061914366069</xMsgID>\n" +
              "    <xCode>0</xCode>\n" +
              "    <xSign>c23f06e20ded02804a4d1d63ca1320c8</xSign>\n" +
              "    <xValue>\n" +
              "        <Project id=\"9003122018061914366000\" chipmoney=\"8.0\" code=\"1\" message=\"成功，已出票\">\n" +
              "            <bill id=\"b89faaf153a7a7bfea17\" billtime=\"2018-06-19 21:15:11\" playid=\"CBF\" maxbonu=\"19.94\" passway=\"2*1\" multi=\"4\">\n" +
              "                <match id=\"180621021\">2:0=1.34</match>\n" +
              "                <match id=\"180621022\">2:1=3.72</match>\n" +
              "            </bill>\n" +
              "        </Project>\n" +
              "        <Project id=\"9003122018061914366001\" chipmoney=\"8.0\" code=\"1\" message=\"成功，已出票\">\n" +
              "            <bill id=\"b89faaf153a7a7bfea17\" billtime=\"2018-06-19 21:15:11\" playid=\"CBF\" maxbonu=\"19.94\" passway=\"2*1\" multi=\"4\">\n" +
              "                <match id=\"180621021\">2:0=1.34</match>\n" +
              "                <match id=\"180621022\">2:1=3.72</match>\n" +
              "            </bill>\n" +
              "        </Project>\n" +
              "    </xValue>\n" +
              "</ActionResult>";
      //System.out.println(getMessageXml);
      //Document doc = Jsoup.parse(getMessageXml);
      //String xml="<batchSendResp><sendResp><sms><phone>137000000</phone><smsID>ff8080813349da9001334f0eed8c5923</smsID></sms></sendResp><sendResp><sms><phone>187000000</phone><smsID>ff8080813349da9001334f0eee045924</smsID></sms></sendResp></batchSendResp>";
      Document doc = DocumentHelper.parseText(getMessageXml);
      System.out.println(doc);


      System.out.println(doc.selectSingleNode("//Project[@id='9003122018061914366000']").asXML());





      /*GetLog getLog = new GetLog();
      HashMap<String,String> envInfo = REMOTE_ENV_MAP.get("STABLE_TASK");
      getLog.versouSshUtil(envInfo.get("host"),Integer.parseInt(envInfo.get("port")),envInfo.get("username"),envInfo.get("password"));
      String ticketId ="180011632018062114853482";
      String getMessageCmd = "grep -E "+ betSelector.replace("{ticketId}",ticketId) + TASK_LOG_DIR;
      System.out.println(getMessageCmd);
      getLog.getLogByTicketId(ticketId,getMessageCmd);
*/



      /*GetLog getLog = new GetLog();
      HashMap<String,String> envInfo = REMOTE_ENV_MAP.get("STABLE_TASK");
      getLog.versouSshUtil(envInfo.get("host"),Integer.parseInt(envInfo.get("port")),envInfo.get("username"),envInfo.get("password"));
      String keyStart = "【1】";
      String keyEnd = "【2】";
      String ticketId ="180011632018062114853482";
      String getMessageCmd = "grep "+ ticketId +" "+ TASK_LOG_DIR;
      System.out.println(getMessageCmd);
      String getMessage = getLog.runCmd(getMessageCmd,"UTF-8");
      if(getMessage == null || getMessage==""){
         System.out.println("error:找不到日志,ticketId:"+ticketId);
      }
      String originMsg = getMessage.substring(getMessage.indexOf(keyStart)+keyStart.length(),getMessage.indexOf(keyEnd));
      System.out.println(originMsg);
      Parser parser = new Parser();
      parser.getStrMsgByTicketId(ticketId,yaosenBetSelector,originMsg);
*/




      /*String getMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
              "\n" +
              "<body> \n" +
              "  <tickets> \n" +
              "    <ticket> \n" +
              "      <ordersID>商户订单号</ordersID>  \n" +
              "      <ticketId>票号(彩票落地号)</ticketId>  \n" +
              "      <status>状态</status>  \n" +
              "      <printTime>时间</printTime>  \n" +
              "      <odds>赔率</odds> \n" +
              "    </ticket>  \n" +
              "    <ticket> \n" +
              "      <ordersID>商户订单号1</ordersID>  \n" +
              "      <ticketId>票号(彩票落地号)</ticketId>  \n" +
              "      <status>状态</status>  \n" +
              "      <printTime>时间</printTime>  \n" +
              "      <odds>赔率</odds> \n" +
              "    </ticket> \n" +
              "  </tickets> \n" +
              "</body>\n";
      Document doc = DocumentHelper.parseText(getMessage);
      //String msg = getLog.getTicketLog("商户订单号1",yaosenSelector,getMessage);
      String ticketId = "商户订单号2";
      String selector = yaosenResendSelector.replace("{ticketId}",ticketId);
      System.out.println(selector);


      if(doc.selectSingleNode(selector) == null){
         System.out.println("未找到该票号信息");
         return;
      }
      String msg = doc.selectSingleNode(selector).asXML();
         System.out.println(msg);



      //GetLog getLog = new GetLog();



      *//*GetLog getLog = new GetLog();
      getLog.versouSshUtil("172.16.36.155",8822,"wangzheng1","r3faX]Tw");
      String ticketId = "9003122018061914366001";
      String logDir = " /home/project/task.s.rrzcp8/log/lottery.log.2018-06-19-21";
      String key = "【http receive】";
      //grep -E  "【http receive】.*9003122018061914366000" lottery.log
      String getMessageCmd = "grep -E \""+key+".*" + ticketId +"\""+ logDir;
      //System.out.println(getMessageCmd);
      //System.out.println(getLog.runCmd(getMessageCmd,"UTF-8"));
      String getMessage = getLog.runCmd(getMessageCmd,"UTF-8");

      //String getMessage = "2018-06-19 21:18:16,659 - com.netease.lottery.core.cooperation.comontransfer.configmethod.ConfigSend2Center [http-nio-8004-exec-1] INFO  com.netease.lottery.core.cooperation.comontransfer.configmethod.ConfigSend2Center  com.netease.lottery.core.cooperation.comontransfer.configmethod.ConfigSend2Center.httpSend(ConfigSend2Center.java:69) - 【亿威通达Sport】【http receive】<?xml version=\"1.0\" encoding=\"gb2312\"?><ActionResult><xMsgID>9003122018061914366069</xMsgID><xCode>0</xCode><xSign>c23f06e20ded02804a4d1d63ca1320c8</xSign><xValue><Project id=\"9003122018061914366000\" chipmoney=\"8.0\" code=\"1\" message=\"成功，已出票\"><bill id=\"b89faaf153a7a7bfea17\" billtime=\"2018-06-19 21:15:11\" playid=\"CBF\" maxbonu=\"19.94\" passway=\"2*1\" multi=\"4\"> <match id=\"180621021\">2:0=1.34</match><match id=\"180621022\">2:1=3.72</match></bill></Project></xValue></ActionResult>\n";
      String getMessageXml = getMessage.substring(getMessage.indexOf(key)+key.length());
    *//**//*  String getMessageXml = "<?xml version=\"1.0\" encoding=\"gb2312\"?>\n" +
              "<ActionResult>\n" +
              "    <xMsgID>9003122018061914366069</xMsgID>\n" +
              "    <xCode>0</xCode>\n" +
              "    <xSign>c23f06e20ded02804a4d1d63ca1320c8</xSign>\n" +
              "    <xValue>\n" +
              "        <Project id=\"9003122018061914366000\" chipmoney=\"8.0\" code=\"1\" message=\"成功，已出票\">\n" +
              "            <bill id=\"b89faaf153a7a7bfea17\" billtime=\"2018-06-19 21:15:11\" playid=\"CBF\" maxbonu=\"19.94\" passway=\"2*1\" multi=\"4\">\n" +
              "                <match id=\"180621021\">2:0=1.34</match>\n" +
              "                <match id=\"180621022\">2:1=3.72</match>\n" +
              "            </bill>\n" +
              "        </Project>\n" +
              "        <Project id=\"9003122018061914366001\" chipmoney=\"8.0\" code=\"1\" message=\"成功，已出票\">\n" +
              "            <bill id=\"b89faaf153a7a7bfea17\" billtime=\"2018-06-19 21:15:11\" playid=\"CBF\" maxbonu=\"19.94\" passway=\"2*1\" multi=\"4\">\n" +
              "                <match id=\"180621021\">2:0=1.34</match>\n" +
              "                <match id=\"180621022\">2:1=3.72</match>\n" +
              "            </bill>\n" +
              "        </Project>\n" +
              "    </xValue>\n" +
              "</ActionResult>";*//**//*
      //System.out.println(getMessageXml);
      //Document doc = Jsoup.parse(getMessageXml);
      //String xml="<batchSendResp><sendResp><sms><phone>137000000</phone><smsID>ff8080813349da9001334f0eed8c5923</smsID></sms></sendResp><sendResp><sms><phone>187000000</phone><smsID>ff8080813349da9001334f0eee045924</smsID></sms></sendResp></batchSendResp>";
      Document doc = DocumentHelper.parseText(getMessageXml);
      System.out.println(doc);


      System.out.println(doc.selectSingleNode("//Project[@id='9003122018061914366000']").asXML());

//      session.disconnect();
*/
   }
}
